import {
    reqGetCode,
    reqUserRegister,
    reqUserLogin,
    userInfo,
    reqLogout
} from '@/api'
import {
    setToken,
    getToken,
    clearToken
} from '@/utils/token.js'
const state = {
    code: '',
    token: getToken(),
    userInfo: {}
}
const actions = {
    // 获取验证码  返回的是验证码  但是正常情况下 是发送给用户 但是为了省钱就直接发送到控制区
    async getCode({
        commit
    }, phone) {
        let result = await reqGetCode(phone)
        // console.log(result);
        if (result.code === 200) {
            commit('GETCODE', result.data)
            return 'OK'
        } else {
            return Promise.reject(new Error('false'))
        }
    },
    // 用户注册
    async userRegister({
        commit
    }, data) {
        let result = await reqUserRegister(data)
        // console.log(result);
        if (result.code === 200) {
            return 'OK'
        } else {
            return Promise.reject(new Error('false'))
        }
    },
    // 登录
    async userLogin({
        commit
    }, data) {
        let result = await reqUserLogin(data)
        // console.log(result);
        // result.data.token   用户唯一标识
        if (result.code === 200) {
            setToken(result.data.token)
            commit('USERLOGIN', result.data.token)
            return 'OK'
        } else {
            return Promise.reject(new Error('false'))
        }
    },
    // 获取用户信息
    async getUserInfo({
        commit
    }) {
        let result = await userInfo()
        // console.log(result);
        if (result.code === 200) {
            commit('USERINFO', result.data)
        }
    },
    // 退出登录
    async Logout({
        commit
    }) {
        let result = await reqLogout()
        if (result.code === 200) {
            commit('LOGOUT')
            return 'OK'
        } else {
            return Promise.reject(new Error('false'))
        }
    }
}
const mutations = {
    GETCODE(state, code) {
        state.code = code
    },
    // 用户登录
    USERLOGIN(state, token) {
        state.token = token
    },
    USERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    LOGOUT(state) {
        state.token = ''
        state.userInfo = {}
        // 清除本地存储
        clearToken()
    }
}
const getters = {}
export default {
    state,
    actions,
    mutations,
    getters
}